package com.whsxt.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-18 17:10
 * @Description: 全局异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 授权异常
     *
     * @return
     */
    @ExceptionHandler({AuthenticationException.class})
    public ResponseEntity<String> authException() {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("你的登录过期，请重新登录");
    }

    /**
     * 参数异常
     *
     * @param e * @return
     */
    @ExceptionHandler({IllegalArgumentException.class})
    public ResponseEntity<String> paramException(IllegalArgumentException e) {
        return ResponseEntity.badRequest().body(e.getMessage());
    }

    /**
     * 运行时异常
     *
     * @param e * @return
     */
    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<String> runtimeException(RuntimeException e) {
        log.error("运行异常", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器维修中!");
    }

    /**
     * 方法参数校验异常
     *
     * @param bindException
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseEntity<String> methodArgumentNotValidException(MethodArgumentNotValidException
                                                                          bindException) {
        BindingResult bindingResult = bindException.getBindingResult();
        System.out.println(bindingResult);
        StringBuilder sb = new StringBuilder("数据校验失败，原因是:");
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            sb.append("字段:" + fieldError.getField() + "," + fieldError.getDefaultMessage() + "!");
        }
        return ResponseEntity.badRequest().body(sb.toString());
    }


}
